<template>
  <div class="addDialg">
    <el-dialog
      :close-on-click-modal="false"
      :title="titleName"
      :visible.sync="dialogTableVisible"
      width="80%">
      <div class="pageTop">
        <el-form :rules="rules" :model="addDialgData" ref="addDialgData" :inline="true" class="inputWidth"  style="padding: 0px 10px; padding-top: 20px;" >
          <el-form-item label="入库仓库" prop="comeWarehouseId">
            <el-select
              v-model="addDialgData.comeWarehouseId"
              placeholder="请选择"
              clearable
              size="medium">
              <el-option
                v-for=" item in gysList"
                :key="item.warehouseId"
                :label="item.warehouseName"
                :value="item.warehouseId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="单据日期"  prop="productionTime">
            <el-date-picker
              v-model="addDialgData.productionTime"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="入库单号" prop="procurementCode">
            <el-input show-overflow-tooltip  size="medium" disabled placeholder="请选择入库单号" v-model="addDialgData.procurementCode" class="input-with-select">
              <el-button @click="handleIconClickDh" slot="append" icon="el-icon-more"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="备注" >
            <el-input  maxlength="250" show-word-limit  size="medium"  v-model="addDialgData.remark" placeholder="请输入备注"></el-input>
          </el-form-item>
          <el-form-item label="单据编号：">
            {{addDialgData.productionCode}}
          </el-form-item>

        </el-form>
      </div>
      <el-table  height="350" v-loading="loading" :data="addDialgData.infos" stripe border style="margin-top: 20px" :header-cell-style="{background:'#eef1f6',color:'#606266'}">
        <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
        <el-table-column align="center" label="原料商品"   property="goodsName" width="200"> </el-table-column>
        <el-table-column align="center" label="商品编号"   property="goodsId"></el-table-column>
        <el-table-column align="center" label="商品编码"   property="goodsSn"></el-table-column>
        <el-table-column align="center" label="商品规格"   property="goodsWeight"></el-table-column>
        <el-table-column align="center" label="采购单位"   property="purchaseUnit"></el-table-column>
        <el-table-column align="center" label="销售单位"   property="goodsUnit"></el-table-column>
        <el-table-column align="center" label="成品金额"   property="shopPrice"></el-table-column>

        <el-table-column align="center" label="原料入库数量"   property="storageCount"></el-table-column>
        <el-table-column align="center" label="生产数量"   property="proCount">
          <template slot-scope="scope">
            <el-input @change="jiantingshul" v-show="scope.row.goodsId" onkeyup="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')"  v-model="scope.row.proCount" placeholder=""></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注"   property="remark" width="200">
          <template slot-scope="scope">
            <el-input  maxlength="250" show-word-limit v-show="scope.row.goodsId" v-model="scope.row.remark"  placeholder="备注"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <div style="height: 50px;line-height: 50px;">
        <span style="margin-left: 50px"><b>合计：</b> </span>
        <span style="margin-left: 20px">库存数量：{{addDialgData.productionCount}}</span>
        <span style="margin-left: 20px">库存金额：{{addDialgData.productionMoney}}</span>
        <span style="margin-left: 20px">生产数量：{{addDialgData.finishedProductCount}}</span>
        <span style="margin-left: 20px">生产金额：{{addDialgData.finishedProductMoney}}元</span>
      </div>
      <div class="pageTop">
        <el-form :model="addDialgData" ref="addDialgData" :inline="true" class="inputWidth"  style="padding: 0px 10px; padding-top: 20px;" label-width="100px" >
          <el-form-item label="生产人：">
            {{yunyingName}}
          </el-form-item>
          <el-form-item label="下单时间：" v-show="addData.leixing=='put'">
            {{addDialgData.crtTime}}
          </el-form-item>
          <el-form-item label="审核人：" v-show="addData.leixing=='put'">
            {{addDialgData.auditUserName}}
          </el-form-item>
          <el-form-item label="审核时间：" v-show="addData.leixing=='put'">
            {{addDialgData.auditTime}}
          </el-form-item>
          <el-form-item label="审核状态：" v-show="addData.leixing=='put'">
            <span v-show="zhuangtai==2" style="color: red">待审核</span>
            <span v-show="zhuangtai==3" style="color: red">审核通过</span>
            <span v-show="zhuangtai==4" style="color: red">驳回</span>
          </el-form-item>
          <el-form-item label="" style="float: right">
            <el-button v-if="auditQX==1"  type="primary" size="medium" @click="shBtn" v-show="addData.leixing=='put' && zhuangtai==2 ||zhuangtai==4 " >审核</el-button>
            <el-button v-if="auditQX==1"  type="primary" size="medium" @click="fsBtn" v-show="addData.leixing=='put' && zhuangtai==3 ">反审</el-button>
            <el-button v-if="addQX==1" type="success"  size="medium" @click="saveBtn" v-show="addData.leixing=='post' || zhuangtai==2 ||zhuangtai==4">保存</el-button>
<!--            <el-button type="danger" size="medium" @click="delBtn" >删除</el-button>-->
          </el-form-item>
        </el-form>
      </div>
    </el-dialog>
    <ruku-Dialog v-if="cgdShow" :shnagpinData="cgdData" @callback="rkback"></ruku-Dialog>
  </div>
</template>

<script>
import request from '@/utils/request'
import rukuDialog from '../../components/rukuDialog'
import {DeleteJL,focusXL,selectCG,getnewDat} from "@/utils/index"
export default {
  props: ['addData'],
  name: "Role",
  components:{
    rukuDialog
  },
  data() {
    return {
      // 表单校验
      rules: {
        comeWarehouseId: [
          { required: true, message: "入库仓库不能为空", trigger: "blur" }
        ],
        productionTime: [
          { required: true, message: "单据日期不能为空", trigger: "blur" }
        ],
        procurementCode: [
          { required: true, message: "入库单号不能为空", trigger: "blur" }
        ],
      },
      deleteQX:localStorage.getItem("delete"),//删除权限
      addQX:localStorage.getItem("add"),//保存权限
      auditQX:localStorage.getItem("audit"),//审核权
      yunyingName:localStorage.getItem("loginUserName"),
      zhuangtai:2,
      cgdShow:false,
      cgdData:{},
      shnagpinData:{},
      shangpinShow:false,
      xiabiao:0,
      restaurants: [],
      leixing:'post',
      titleName:'新增生产单',
      loading:false,
      //付款日期
      fkDateList:[],
      dialogTableVisible:true,
      modifyData:{
        productionCode:'',
        infos:[],
      },
      //新增的参数列表
      addDialgData: {
        comeWarehouseId: '',
        productionCode: "",
        productionTime: "",
        productionCount:0,
        productionMoney:0,
        finishedProductCount:0,
        finishedProductMoney:0,
        infos: [],
      },
      //供应商
      gysList:[],
      timestamp:(new Date()).getTime()
    };
  },

  watch: {
    dialogTableVisible: function () {
      this.dialogTableVisible = true;//始终让他为true;
      this.cancel();//隐藏
    },
  },
  created() {
    this.addDialgData.productionCode ='SC'+Date.parse(new Date())/1000;
    this.zhuangtai = this.addData.purchasePlanStatus
    var arr =  getnewDat()
    this.addDialgData.productionTime = arr[0]
    this.getshangpin();
    this.getCKList();
    console.log('接受',this.addData)
    if(this.addData.leixing=='put'){
      this.titleName = '修改生产单'
      this.gethuixian()
    }
  },
  mounted() {
  },
  methods: {
    //监听数量
    jiantingshul:function (){
      this.jisuanshuliang(this.addDialgData.infos)
    },
    //获取回显数据
    gethuixian:function () {
      this.loading = true
      request({
        url: '/wh/production/getById/' + this.addData.id,
        method: 'get',
      }).then(response => {
        this.loading = false
        if(response.code==200){
          this.addDialgData = response.data
          for(var i=0;i<this.addDialgData.infos.length;i++){
            this.addDialgData.infos[i].inventory= this.addDialgData.infos[i].materialCount
            // this.addDialgData.infos[i].proPrice= this.addDialgData.infos[i].materialCount

          }

          this.jisuanshuliang(this.addDialgData.infos)
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }

      });
    },
     //添加
    addBtn:function (){
      this.addDialgData.infos.push(
        {
          // productionCode 生产单号
          goodsId:'',
          goodsSn:'', //商品编码
          goodsName:'',  //商品名称
          goodsUnit:'',  //单位
          batchCode:'',  //原料入库批次
          purchaseUnit:'', //采购单位
          materialCount:'',  //原料数量
          receiveCount:'',   //领料数量
          proUnit:'',// 生产单位
          specifications:'',//  产品规格
          proBatch:'',// 生产批次
          proPrice:'0', //成品金额
          proCount:'1',// 成品份数
          remark:'' // 备注
        },
      )
    },
    //采购单号点击
    handleIconClickDh(ev) {
      console.log('点击',ev);
      this.cgdShow = true
    },
    //查询仓库
    getCKList:function (){
      request({
        url: '/wh/warehouse/list?isAllot=1&isMaterial=2',
        method: 'get',
      }).then(response => {
        this.gysList = response.data
        this.addDialgData.comeWarehouseId =response.data[0].warehouseId
      });
    },
    //获取下拉焦点
    focusBtn:function (index,row){
      focusXL(index)
    },
    //获取所有商品
    getshangpin:function (){
      var obj={}
      obj.current = 1
      obj.size= 10000
      request({
        url: '/wh/putStorageInfo/page',
        method: 'get',
        params:obj
      }).then(response => {
        this.restaurants = response.data.records
        for (var i=0;i<this.restaurants.length;i++){
          this.restaurants[i].value =  this.restaurants[i].goodsSn
        }
      });
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      console.log('选择商品',item);
      selectCG(item,this.addDialgData.infos,this)
      this.jisuanshuliang(this.addDialgData.infos)
    },
    //计算页面数据
    jisuanshuliang:function (ymArr){
      var sum=0;
      var jine=0;
      var kunsum=0
      var kcjine=0
      debugger
      console.log('arr',ymArr)
      for (var i=0;i<ymArr.length;i++){
        sum=sum+ymArr[i].proCount*1;
        kunsum=kunsum+ymArr[i].storageCount*1;

        jine=jine+ymArr[i].shopPrice*1*ymArr[i].proCount
        kcjine=kcjine+ymArr[i].storageCount*1*ymArr[i].procurementMoney
      }
      this.addDialgData.finishedProductCount=sum;
      this.addDialgData.finishedProductMoney= Math.round (jine*100)/100;
      this.addDialgData.productionCount = kunsum
      this.addDialgData.productionMoney =  Math.round (kcjine*100)/100;

    },
    handleIconClick(ev) {
      console.log('点击',ev);
      this.cgdShow = true
    },
    //入库回调
    rkback:function (msg){
      this.cgdShow = false
      if(!msg){
        return
      }
      this.addDialgData.procurementCode = msg.rukucode
      console.log('msg',msg)
      if(msg.radioId){
        this.gethdSP(msg.rukucode)
      }
    },
    //获取回调函数商品
    gethdSP:function (code){
      this.loading = true
      var obj={}
      obj.current = 1
      obj.size = 1000
      obj.putStorageCode = code
      request({
        url: '/wh/putStorageInfo/findStoragePage',
        method: 'get',
        params:obj
      }).then(response => {
        this.loading = false
        if(response.code=='200'){
          this.addDialgData.infos = response.data.records
          this.jisuanshuliang(this.addDialgData.infos)
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }

      });

    },
    //弹框回调
    callback:function (item){
      this.shangpinShow = false
      if(!item){
        return
      }
      var arr= this.addDialgData.infos
      arr = arr.concat(item)
      this.addDialgData.infos = arr
      for(var i=0;i<this.addDialgData.infos.length;i++){
        if( this.addDialgData.infos[i].goodsId==''){//解决初始化id为空导致多一条空数据
          this.addDialgData.infos.splice(i,1);
        }
        this.addDialgData.infos[i].proPrice = this.addDialgData.infos[i].procurementMoney
      }
      this.jisuanshuliang(this.addDialgData.infos)

    },
    //去重
    deteleObject:function(data){
      let hash = {};
      const data2 = data.reduce((preVal, curVal) => {
        console.log(curVal)
        hash[curVal.id] ? '' : hash[curVal.id] = true && preVal.push(curVal);
        return preVal
      }, [])
      return data2
    },
    //删除采购单
    delBtn:function (){
      this.$confirm('此操作将删除采购单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //保存
    saveBtn:function (){
      if(!this.addDialgData.productionTime){
        this.$message({
          type: 'warning',
          message:'单据日期不能为空！'
        });
        return
      }
      if(!this.addDialgData.comeWarehouseId){
        this.$message({
          type: 'warning',
          message:'未选择仓库！'
        });
        return
      }
      if(!this.addDialgData.procurementCode){
        this.$message({
          type: 'warning',
          message:'未选择入库单号！'
        });
        return
      }
      for(var i=0;i<this.addDialgData.infos.length;i++){
        if(!this.addDialgData.infos[i].proCount){
          this.$message({
            type: 'warning',
            message:'有商品未填写生产数量！'
          });
          return
        }

      }

      if(this.addData.leixing=='put'){//修改
        request({
          url: '/wh/production/update',
          method: 'PUT',
          data:this.addDialgData
        }).then(response => {
          this.cancel();//隐藏
          if(response.code=='200'){
            this.$message({
              type: 'success',
              message:response.msg
            });
          }else {
            this.$message({
              type: 'warning',
              message:response.msg
            });
          }

        });
        return
      }
      //新增
      request({
        url: '/wh/production/add',
        method: 'post',
        data:this.addDialgData
      }).then(response => {
        this.cancel();//隐藏
        if(response.code=='200'){
          this.$message({
            type: 'success',
            message:response.msg
          });
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }

      });


    },
    //审核
    shBtn:function (){
      this.$confirm('此操作将审核通过, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.shenhe();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消审核'
        });
      });
    },
    //审核
    shenhe:function (row){
      request({
        url: '/wh/production/audit?id='+this.addData.id,
        method: 'put',
      }).then(response => {
        if(response.code==200){
          this.$message({
            type: 'success',
            message:response.msg
          });
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }
        this.cancel();//隐藏
      });
    },
    //反审
    fsBtn:function (){
      this.$confirm('此操作将反审, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.bohui();
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消反审'
        });
      });
    },
    //驳回
    bohui:function (row){
      request({
        url: '/wh/production/rejected?id='+this.addData.id,
        method: 'put',
      }).then(response => {
        if(response.code==200){
          this.$message({
            type: 'success',
            message:response.msg
          });
        }else {
          this.$message({
            type: 'warning',
            message:response.msg
          });
        }
        this.cancel();//隐藏
      });
    },
    //删除
    handleDelete:function (index,row){
      DeleteJL(index,row,this.addDialgData.infos,this.modifyData.infos)
      this.jisuanshuliang(this.addDialgData.infos)
    },
    //确定
    determine:function(){

      this.$emit('callback','参书')//将submitModel的值传给父组件
    },
    //隐藏
    cancel:function(){
      // this.determine()
      this.$emit('callback','')//将submitModel的值传给父组件
    },

  }
};
</script>
<style scoped>
.addDialg {

}


</style>
